﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows.Threading;

namespace MediaPlayer
{
	public partial class MiniPlayer : UserControl
    {
        private TimeSpan _duration;

        private DispatcherTimer _timer = new DispatcherTimer();

        public string MediaUrl
        {
            get { return GetValue(MediaUrlProperty).ToString(); }

            set { SetValue(MediaUrlProperty, value); }
        }

        public new Brush Background
        {
            get { return GetValue(BackgroundProperty) as Brush; }

            set { SetValue(BackgroundProperty, value); }
        }

        public static readonly DependencyProperty MediaUrlProperty = DependencyProperty.Register("MediaUrl", typeof(string), typeof(MiniPlayer), new PropertyMetadata("", new PropertyChangedCallback(OnMediaUrlPropertyChanged)));
        public static new readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(MiniPlayer), new PropertyMetadata(new SolidColorBrush(Colors.Transparent), new PropertyChangedCallback(OnBackgroundPropertyChanged)));

		public MiniPlayer()
		{
			// Required to initialize variables
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Player_Loaded);
            mediaElem.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>(mediaElem_MediaFailed);
            mediaElem.MediaOpened += new RoutedEventHandler(mediaElem_MediaOpened);
            mediaElem.MediaEnded += new RoutedEventHandler(mediaElem_MediaEnded);
            mediaElem.CurrentStateChanged += new RoutedEventHandler(mediaElem_CurrentStateChanged);
            mediaElem.BufferingProgressChanged += new RoutedEventHandler(mediaElem_BufferingProgressChanged);
            mediaElem.DownloadProgressChanged += new RoutedEventHandler(mediaElem_DownloadProgressChanged);
            volBarControl.VolChanged += new VolBarControl.VolChangedHandler(volBarControl_VolChanged);
        }

        void volBarControl_VolChanged(object sender)
        {
            mediaElem.Volume = (double) (sender as VolBarControl).VolLevel / 6.0;
        }

        private static void OnMediaUrlPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MiniPlayer miniPlayer = d as MiniPlayer;
            miniPlayer.SetMediaUrl(e.NewValue.ToString());
        }

        private static void OnBackgroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MiniPlayer miniPlayer = d as MiniPlayer;
            miniPlayer.SetBackgroundBrush(e.NewValue as Brush);
        }

        public void SetMediaUrl(string url)
        {
            Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);
            mediaElem.Source = uri;
        }

        public void SetBackgroundBrush(Brush brush)
        {
            basePath.Fill = brush;
        }

        private void Player_Loaded(object sender, RoutedEventArgs e)
        {
            // 每 500 毫秒调用一次指定的方法
            _timer.Interval = TimeSpan.FromMilliseconds(500);
            _timer.Tick += new EventHandler(timer_Tick);
            _timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            // CurrentState - 播放状态 [System.Windows.Media.MediaElementState枚举]
            // Position - 媒体的位置（单位：秒）
            if (mediaElem.CurrentState == MediaElementState.Playing)
            {
                playerInfo.Text = string.Format(
                    "{0}{1:00}:{2:00}:{3:00}",
                    "播放进度：",
                    mediaElem.Position.Hours,
                    mediaElem.Position.Minutes,
                    mediaElem.Position.Seconds);
                if (_duration != null && _duration.TotalSeconds > 0)
                {
                    positionBar_scaleTransform.ScaleX = mediaElem.Position.TotalSeconds / _duration.TotalSeconds;
                }
            }
        }

        void mediaElem_DownloadProgressChanged(object sender, RoutedEventArgs e)
        {
            MediaElement media = sender as MediaElement;
        }

        void mediaElem_BufferingProgressChanged(object sender, RoutedEventArgs e)
        {
            MediaElement media = sender as MediaElement;
        }

        void mediaElem_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            string info = "";
            MediaElement media = sender as MediaElement;
            switch (media.CurrentState)
            {
            case MediaElementState.AcquiringLicense:
                    info = "正在获取播放该媒体所需要DRM许可证…";
                    break;
            case MediaElementState.Buffering:
                    info = "缓冲中…";
                    break;
            case MediaElementState.Closed:
                    info = "未打开任何媒体文件。";
                    break;
            case MediaElementState.Individualizing:
                    info = "检查所需DRM许可证中…";
                    break;
            case MediaElementState.Opening:
                    info = "媒体打开中…";
                    break;
            case MediaElementState.Paused:
                    VisualStateManager.GoToState(this, "Normal", true);
                    info = "已暂停。";
                    pauseBtn.Visibility = Visibility.Collapsed;
                    VisualStateManager.GoToState(pauseBtn, "Normal", true);
                    playBtn.Visibility = Visibility.Visible;
                    DiskImgPlaying.Stop();
                    break;
            case MediaElementState.Playing:
                    VisualStateManager.GoToState(this, "ReadytoPlay", true);
                    info = "播放中…";
                    playBtn.Visibility = Visibility.Collapsed;
                    VisualStateManager.GoToState(playBtn, "Normal", true);
                    pauseBtn.Visibility = Visibility.Visible;
                    DiskImgPlaying.Begin();
                    break;
            case MediaElementState.Stopped:
                    VisualStateManager.GoToState(this, "Normal", true);
                    info = "播放停止。";
                    pauseBtn.Visibility = Visibility.Collapsed;
                    VisualStateManager.GoToState(pauseBtn, "Normal", true);
                    playBtn.Visibility = Visibility.Visible;
                    DiskImgPlaying.Stop();
                    break;
            default:
                    break;
            }
            playerInfo.Text = info;        
        }

        void mediaElem_MediaEnded(object sender, RoutedEventArgs e)
        {
            MediaElement media = sender as MediaElement;
            playerInfo.Text = "播放停止。";     
            media.Stop();
        }

        void mediaElem_MediaOpened(object sender, RoutedEventArgs e)
        {
            MediaElement media = sender as MediaElement;
            media.Stop();
            positionBar_scaleTransform.ScaleX = 0;
            _duration = media.NaturalDuration.TimeSpan;
        }

        void mediaElem_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            MediaElement media = sender as MediaElement;
            playerInfo.Text = "媒体文件载入失败。";
        }

        private void playBtn_Click(object sender, RoutedEventArgs e)
        {
            mediaElem.Play();
        }

        private void pauseBtn_Click(object sender, RoutedEventArgs e)
        {
            mediaElem.Pause();
        }

        private void volBtn_Click(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "AdjustVol", true);
        }
	}
}